
"use strict";
const Service = require("egg").Service;
const { failRes, successRes } = require("../extend/helper");
const { Journal } = require("../exception/Journal");
const { Op } = require("sequelize");
const await = require("await-stream-ready/lib/await");

function toInt(str) {
  if (typeof str === "number") return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class sShoppings extends Service {
  // wc 购物车查询
  async wa_s_query(params) {
    console.log("params: ", params);
    const { ctx } = this;
    let response = null;
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);
      const totols = await ctx.model.Shoppingcarts.count({
        where: {
          uid: params?.uid ?? "",
        },
      })
      const result = await ctx.model.Shoppingcarts.findAndCountAll({
        where: {
          uid: params?.uid ?? "",
        },
        include: [
          {
            model: ctx.model.Users,
          },
          {
            model: ctx.model.Products,
            through: { attributes: ["id", "pcount", "sprice"] },
          },
        ],
        order: [["updatedAt", "ASC"]], // 排序
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      });
      await Journal(ctx, { operatorType: "购物车信息 -> 查询", code: 200 });
      response = successRes({
        records: result?.rows ?? [],
        total: totols || 0,
        pageSize,
        currentPage,
      });
    } catch (error) {
      console.log("error: ", error);
      await Journal(ctx, { operatorType: "购物车信息 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }


  //wc删除购物车单个商品
  async wa_s_delete_one(params) {
    let response = null;
    const { ctx } = this;
    try {
      await ctx.model.ShoppingcartsProducts.destroy(
        {
          where: { id: params.id },
        }
      );
      await Journal(ctx, { operatorType: '购物车单个商品 -> 删除', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 购物车单个商品删除');
      await Journal(ctx, { operatorType: '购物车单个商品 -> 删除', code: 401 });
      response = failRes(401);
    }
    return response;
  }
  //wc删除购物车多个商品
  async wa_s_deleteMany(params) {
    let response = null;
    const { ctx } = this;
    let transaction = await ctx.model.transaction();
    try {
      const result = await ctx.model.Shoppingcarts.findOne({
        where: {
          uid: params.uid,
        },
      }, { transaction });
      if (result) {
        await ctx.model.ShoppingcartsProducts.destroy({
          where: {
            sid: result?.id ?? "",
          },
        }, { transaction })
      };
      transaction.commit();
      await Journal(ctx, { operatorType: '购物车商品 -> 批量删除', code: 200 });
      response = successRes();
    } catch (error) {
      transaction.rollback();
      console.error(error, '<---- error - 购物车商品批量删除');
      await Journal(ctx, { operatorType: '购物车商品 -> 批量删除', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 创建预订单
  async wa_s_createOrders(params) {
    console.log(params, '<---- params - 创建预订单');
    const { ctx } = this;
    let response = null;
    let transaction = await ctx.model.transaction();
    try {
      const result = await ctx.model.Orders.create({
        uid: params?.uid ?? "",
        status: 1,
        totals: params?.totals ?? 0,
        remark: params?.remark ?? "",
        aid: params?.aid ?? "",
        // coupon_totals: "88.88" ,
        coupon_totals: params?.couponTotals ?? "",

        // sprice: params?.sprice ?? 0,
      }, { transaction });
      if (result) {
        // const products = params?.products?.map(product => {
        //   return { oid: result?.id ?? "", pid: product?.pid, pcount: product?.pcount, sprice: product?.sprice ?? 0 };
        // })
        // 删除购物车
        // await ctx.model.ShoppingcartsProducts.destroy({
        //   where: {
        //     pid: { [Op.in]: params?.products?.map(product => product?.pid) },
        //   }
        // }, { transaction });
        // 添加订单商品
        // await ctx.model.OrdersProducts.bulkCreate(products || [], { transaction });

        //查询用户余额
        const userTotals = await ctx.model.Users.findOne({
          where: { id: params?.uid },
          attributes: ['id', 'totals'],
        })
        console.log(userTotals.totals, "<=====")
        //余额大于等于订单总额
        if (userTotals.totals >= params?.totals) {

          // 更改库存r
          await ctx.model.Products.findAll({
            where: {
              id: { [Op.in]: params?.products?.map(product => product?.pid) },
            }
          }).then(async products => {
            for (let i = 0; i < products.length; i++) {

              const product = products[i];
              const id = product?.id ?? 0;
              const _product = params?.products?.find(product => {return product?.pid === id && product.sprice;}); // 加购数量和商品实价
              const pcount = _product?.pcount ?? 0; // 加购数量
              const sprice = _product?.sprice ?? 0; // 商品实价
              const stock = product?.inventory ?? 0; // 商品库存

              if (stock - pcount >= 0) {
                await product.update({ inventory: stock - pcount }, { transaction });

                await ctx.model.OrdersProducts.create({
                  oid: result?.id ?? "",
                  pid: id,
                  pcount: pcount,
                  sprice: sprice,
                }, { transaction });
                // 删除购物车
                await ctx.model.ShoppingcartsProducts.destroy({
                  where: {
                    pid: id,
                  }
                }, { transaction });
              } else {
                console.log("库存不足");
                throw new Error(299);
              }
            }
          })
          await userTotals.update({ totals: (userTotals?.totals - result.totals) }, { transaction })
          console.log(userTotals.totals, "<=====")

        }



      }
      transaction.commit();
      await Journal(ctx, { operatorType: '购物车商品 -> 创建预订单', code: 200 });
      response = successRes();
    } catch (error) {
      console.log(error.message, '<---- error');
      transaction.rollback();
      console.error(error, '<---- error - 购物车商品创建预订单');
      let code = 401;
      if (error?.message === '299') {
        code = 299;
      }
      await Journal(ctx, { operatorType: '购物车商品 -> 创建预订单', code: code });
      response = failRes(code);
    }
    return response;
  }

  //默认地址查询
  async wa_s_queryDefaultAddress(params) {
    const { ctx } = this;
    let response = null;
    try {
      const result = await ctx.model.Address.findOne({
        where: { uid: params?.uid ?? "", is_default: 1 },
      })

      await Journal(ctx, { operatorType: "结算商品信息 -> 查询", code: 200 });
      response = successRes(result);
    }catch (error) {
      console.log("error: ", error);
      await Journal(ctx, { operatorType: "结算商品信息 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  //预结算商品查询
  async wa_s_queryJiesProducts(params) {
    console.log("params: ", params);
    const { ctx } = this;
    let response = null;
    try {

      const result = await ctx.model.Shoppingcarts.findAll({
        where: { uid: params?.uid ?? "", },
        include: [{
          model: ctx.model.Products,
          where: {
            id: {
              [Op.in]: params?.cart_ids ?? [],
            }
          },
          through: { attributes: ["pcount", "sprice"] },
        }],
      });

      await Journal(ctx, { operatorType: "结算商品信息 -> 查询", code: 200 });
      response = successRes(result);
    } catch (error) {
      console.log("error: ", error);
      await Journal(ctx, { operatorType: "结算商品信息 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }



  // 加入购物车
  async wa_s_createShopping(params) {
    const { ctx } = this;
    let response = null;
    let transaction = await ctx.model.transaction();
    try {
      const [result] = await ctx.model.Shoppingcarts.findOrCreate({
        where: {
          uid: params?.uid ?? ""
        },
        defaults: {
          // id: id,
          uid: params?.uid ?? "",
          sprice: params?.sprice ?? "",
        },

      }).catch((error) => { console.error(error, '<---- error - 商品购物车'); });


      if (result) {
        console.log(result, '<---- result - 加入购物车');
        const SPResult = await ctx.model.ShoppingcartsProducts.findOne({
          where: {
            sid: result?.dataValues?.id ?? "",
            pid: params?.pid ?? "",
          },
        }, { transaction });
        if (SPResult) {
          await SPResult.update({ pcount: (SPResult?.pcount + params?.pcount ?? 1), sprice: params?.sprice ?? 99999 }, { transaction });
        } else {
          await ctx.model.ShoppingcartsProducts.create({
            sid: result?.dataValues?.id ?? "",
            pid: params?.pid ?? "",
            pcount: params?.pcount ?? 1,
            sprice: params?.sprice ?? 100000,
          }, { transaction })
        }
      }

      transaction.commit();
      await Journal(ctx, { operatorType: '商品 -> 加入购物车', code: 200 });
      response = successRes();
    } catch (error) {
      transaction.rollback();
      console.error(error, '<---- error - 商品加入购物车');
      await Journal(ctx, { operatorType: '购商品 -> 加入购物车', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  //用户订单查询
  async wa_s_queryOrders(params) {
    console.log("paramsOrders:===============> ", params);
    let response = null;
    const { ctx } = this;
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);

      const count = await ctx.model.Orders.count({
        where: {
          uid: params?.uid ?? "",
          status: {
            [Op.like]: `%${ params?.status ?? ""}%`,
          }
        }
      });

      const result = await ctx.model.Orders.findAndCountAll({
        where: {
          uid: params?.uid ?? "",
          status: {
            [Op.like]: `%${ params?.status ?? ""}%`,
          }
        },
        include: [
          // 关联查询商品分类表
          {
            model: ctx.model.Products,
            // required: true, // 设置为必须关联查询
            attributes: ["id", "title", "price", "defaultImg"], // 指定查询的字段
            // through: { attributes: [] },
            through: { attributes: ["pcount", "sprice"] },
          },
          {
            model: ctx.model.Address,
            // required: true, // 设置为必须关联查询
            attributes: [
              "id",
              "nickName",
              "mobile",
              "provincial",
              "city",
              "address",
              "uid",
            ], // 指定查询的字段
          },
        ],
        order: [["id", "ASC"]], // 排序
        attributes: ["id", "uid", "status", "totals", "remark", "createdAt", "updatedAt"],
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      });
      console.log(result, "<---- 商品订单查询结果 - 商品订单查询");
      await Journal(ctx, { operatorType: "商品订单 -> 查询", code: 200 });
      response = successRes({
        records: result?.rows ?? [],
        total: count || 0,
        pageSize,
        currentPage,
      });
    } catch (error) {
      console.error(error, "<---- error - 商品订单查询");
      await Journal(ctx, { operatorType: "商品订单 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }


}


module.exports = sShoppings;
